﻿using Newtonsoft.Json;
using SM23;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TlToolBase;
using TlToolBase.Mode;
using TlToolCordCreate.Mode;
using TlToolCordCreate.ViewMode;

namespace TlToolCordCreate.Web
{
    /// <summary>
    /// 网络请求
    /// </summary>
    public class MyWebRequest
    {
        HttpHelp _httpHelp { get; set; }
        HttpResultValue _token { get; set; }
        /// <summary>
        /// 服务地址
        /// </summary>
        public string ServerIP { get; set; } = "127.0.0.1";
        /// <summary>
        /// 服务端口
        /// </summary>
        public int ServerPort { get; set; } = 5005;

        /// <summary>
        /// 获取tonek地址
        /// </summary>
        private string apiGetToenk = "http://{0}:{1}/api/sysAuth/login";
        /// <summary>
        /// 添加表
        /// </summary>
        private string apiAddTable = "http://{0}:{1}/api/sysDatabase/addTable";
        /// <summary>
        /// 添加代码
        /// </summary>
        private string apiAddCodeGen = "http://{0}:{1}/api/sysCodeGen/add";
        /// <summary>
        /// 创建实体
        /// </summary>
        private string apiCreateEntity = "http://{0}:{1}/api/sysDatabase/createEntity";
        /// <summary>
        /// 按业务名称创建代码
        /// </summary>
        private string apiRunLocalBusName = "http://{0}:{1}/api/sysCodeGen/runLocalBusName";

        public MyWebRequest()
        {
            _httpHelp = new HttpHelp();
        }

        /// <summary>
        /// 添加表
        /// </summary>
        [Obsolete]
        public void AddTable(DbTableInput input)
        {
            Task.Factory.StartNew(() =>
            {
                var url = string.Format(apiGetToenk, ServerIP, ServerPort);
                var dst = _httpHelp.Post(url, input, _token.result.accessToken);
                dst.Wait(1000);
                try
                {
                    var res = JsonConvert.DeserializeObject<HttpResultValue>(dst.Result);
                    if (res.code == 200)
                    {
                        //action?.Invoke(true);
                    }
                }
                catch (Exception ex)
                {

                }
            });
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="action"></param>
        public void GetToken(Action<bool> action)
        {
            Task.Factory.StartNew(() =>
            {
                var url = string.Format(apiGetToenk, ServerIP, ServerPort);
                var dst = _httpHelp.Post(url, new LoginInput()
                {
                    Account = "admin",
                    Password = SM2Encryption.Encrypt("123456"),
                    Code = "string",
                    CodeId = 0
                });
                dst.Wait(1000);
                try
                {
                    _token = JsonConvert.DeserializeObject<HttpResultValue>(dst.Result);
                    if (_token.code == 200)
                    {
                        action?.Invoke(true);
                    }
                }
                catch (Exception ex)
                {

                }
            });
        }
        /// <summary>
        /// 创建表代码
        /// </summary>
        /// <param name="con"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void CreateTableCode(Config con,string EntityName,string TableName, Action<bool> action)
        {
            Task.Factory.StartNew(() =>
            {
                var url = string.Format(apiCreateEntity, ServerIP, ServerPort);
                var dst = _httpHelp.Post(url, new CreateEntityInput()
                {
                   BaseClassName= ProgramConstant.BaseClassName,
                   ConfigId= con.ConfigId,
                   EntityName= EntityName,
                   Position= con.Position,
                   TableName= TableName,
                }, _token.result.accessToken);
                dst.Wait(1000);
                try
                {
                    var dstres = JsonConvert.DeserializeObject<HttpResultValue>(dst.Result);
                    if (dstres.code == 200)
                    {
                        action?.Invoke(true);
                    }
                }
                catch (Exception ex)
                {

                }
            });
        }

        /// <summary>
        /// 创建业务代码
        /// </summary>
        /// <param name="config"></param>
        /// <param name="v"></param>
        /// <param name="tableName"></param>
        /// <param name="action"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void CreateBusinessCode(UiData config, TableProperties table, Action<bool> action)
        {
            Task.Factory.StartNew(() =>
            {
                var url = string.Format(apiAddCodeGen, ServerIP, ServerPort);
                var dst = _httpHelp.Post(url, new AddCodeGenInput()
                {
                    ConfigId=config.config.ConfigId,
                    TableName= table.ClassName+ table.Suffix,
                    AuthorName= "TlToolCordCreate",
                    BusName= table.TableDescribe,
                    ClassName= table.ClassName,
                    DbType="MySql",
                    ConnectionString=string.Format( "Server={0};User ID={1};Password={2};port=3306;Database={3};CharSet=utf8;pooling=true;SslMode=None;",config.config.dbIp, config.config.dbUser, config.config.dbPasswork, config.config.dbName),
                    GenerateType="121",
                    NameSpace= config.config.Namespace,
                }, _token.result.accessToken);
                dst.Wait(1000);
                try
                {
                    var dstres = JsonConvert.DeserializeObject<HttpResultValue>(dst.Result);
                    if (dstres.code == 200)
                    {
                        action?.Invoke(true);
                    }
                    else
                    {
                        action?.Invoke(false);
                    }
                }
                catch (Exception ex)
                {

                }
            });

        }
        public void RunLocalBusName(UiData config, TableProperties table, Action<bool> action)
        {
            Task.Factory.StartNew(() =>
            {
                var url = string.Format(apiRunLocalBusName, ServerIP, ServerPort);
                var dst = _httpHelp.PostParams(url, new List<Tuple<string, string>>()
                {
                    Tuple.Create("busName",table.TableDescribe)
                }, _token.result.accessToken);
                dst.Wait(1000);
                try
                {
                    var dstres = JsonConvert.DeserializeObject<HttpResultValue>(dst.Result);
                    if (dstres.code == 200)
                    {
                        action?.Invoke(true);
                    }
                }
                catch (Exception ex)
                {

                }
            });

        }
    }
}
